/* typehints:start */
import { GameRoot } from "../root";
/* typehints:end */

import { createID, getObjectType, makeDiv } from "../../core/utils/utils";
import { BaseHUDPart } from "./base_hud_part";

const id = createID();

export class SelectBtnGroup extends BaseHUDPart{
  constructor(root, element, btnDom, btnGroup){
    super(root);
    /** @type {HTMLElement} */
    this.element = element;

    this.btnDom = btnDom;
    this.btnGroup = btnGroup;

    this.otherBtn = {};
    this.defaultBtn = {};

    this.initialize();
  }

  initialize(){
    let btnDom = this.element.querySelector(this.btnDom)

    btnDom.innerHTML = '';

    this.btnGroup.map(btn => {
      let _id = id();

      let dom = makeDiv(btnDom, `btn_${_id}`, ['item', btn.classType || '', btn.active ? 'active' : ''], `${btn.text} <span></span>`);
      // assert(btn.click, '选择菜单按钮中的点击事件不存在');
      this.trackClicks(dom, this.internalBtnClick.bind(this, _id, btn), {
        applyCssClass: ''
      })

      if(btn.otherClick){
        this.otherBtn[_id] = btn.otherClick;
      }

      if(btn.active){
        this.defaultBtn = { _id, btn };
        this.setActive();
      }
    })
  }

  setActive(){
    this.internalBtnClick(this.defaultBtn._id, this.defaultBtn.btn);
  }

  internalDefaultBtnClick(btn){
    if(btn.page){
      let domArr = btn.page.split('|');
      let parent, page;

      if(domArr.length == 1){
        if(this.element.id){
          parent = '#' + this.element.id;
        } else {
          parent = '.' + this.element.className;
        }
        page = domArr[0];
      } else {
        parent = domArr[0];
        page = domArr[1];
      }

      this.selectPage(parent, page);
    }
  }

  internalBtnClick(id, btn){
    let data = btn.click && btn.click.call(this);

    if(getObjectType(data) == 'Boolean' && !data) return;
    
    [...this.element.querySelectorAll(this.btnDom + ' .item')].map(btn => {
      btn.classList.remove('active');
    })

    this.element.querySelector(`#btn_${id}`).classList.add('active');

    this.internalDefaultBtnClick(btn)
    Object.keys(this.otherBtn).map(key => {
      if(key != id) this.otherBtn[key]();
    })
  }

  /**
   * 
   * @param {HTMLElement} parent 
   * @param {*} active 
   */
  selectPage(parent, active){
    [...this.element.querySelectorAll(parent + ' > .page')].map(page => {
      if(!page.classList.contains(active)){
        page.classList.add('remove');
      } else {
        page.classList.remove('remove')
      }
    })
  }
}